<?php

namespace App\Models;

use App\Exceptions\AppException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class AdminModel extends BaseModel
{
    use HasFactory, SoftDeletes;

    protected $table = 't_admin';

    protected $primaryKey = 'id';

    public $timestamps = true;

    const CREATED_AT = 'created_at';
    
    const UPDATED_AT = null;

    protected $guarded = [];

    protected $casts = [
        'created_at'   => 'date:Y-m-d H:i:s',
    ];

    protected $hidden = [
        'deleted_at',
        'password',
        'token'
    ];

    protected static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
            //检查账号是否存在
            $e = AdminModel::where('id', '<>', $model->id)->where('account', $model->account)->first();
            if($e) {
                throw new AppException('账号已存在');
            }
        });
    }

    public function staff(): BelongsTo {
        return $this->belongsTo(StaffModel::class, 'staff_id');
    }

    public function create_admin(): BelongsTo {
        return $this->belongsTo(AdminModel::class, 'created_admin_id');
    }

}
